package com.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.dao.CourseDAO;
import com.dto.CourseDTO;
import com.util.db.DBUtil;

public class CourseDAOImpl implements CourseDAO {
	private Connection conn;

	public CourseDAOImpl() {
		conn = DBUtil.getConnection();
	}

	@Override
	public List<CourseDTO> getCourses() {
		List<CourseDTO> courses = null;
		String sql = "SELECT * FROM course ORDER BY c_id;";
		QueryRunner qr = new QueryRunner();

		try {
			courses = qr.query(conn, sql, new BeanListHandler<CourseDTO>(
					CourseDTO.class));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return courses;
	}

	@Override
	public CourseDTO getCourseById(String course_id) {
		CourseDTO course = null;
		String sql = "SELECT * FROM course WHERE c_id=?";
		QueryRunner qr = new QueryRunner();

		try {
			course = qr.query(conn, sql, new BeanHandler<CourseDTO>(
					CourseDTO.class), course_id);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return course;
	}

}
